;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.BorrowBack", [])
        .controller("BorrowBackCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", "MaterialService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams, MaterialService) {
            $scope.activeFlag = [true, false, false, false];
            $scope.markInfo = {
                allCheckedList: false, // 主列表全选
                allCheckedMaterial: false, // 编辑页面：零件列表全选
                allCheckedBorrowIn: false, // 新增页面：借用单全选
                curRow: -1
            };
            $scope.deleteIdList = [];
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = []; // 主列表
            $scope.dataBorrowInList = []; // 新增页面：借用单列表
            $scope.isBorrowType = [{
                    code: '0',
                    name: '拆'
                },
                {
                    code: '1',
                    name: '借'
                },
            ]
            $scope.tabFlag = {};
            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑",
                3: "详情",
                4: "审核",
            };
            $scope.steps = {
                curStep: 0,
                list: [{
                    name: '选择借用单'
                }, {
                    name: '生成归还单'
                }]
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/serviceBorrowIn/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/serviceBorrowIn/exportAll")
            };
            $scope.orderObj = { // 编辑页：页面上字段
                id: '',
                code: '',
                borrowCode: '',
                serviceInformationMember: '',
                crantNo: '',
                warehouseOut: '',
                warehouseAreaOut: '',
                borrowReasonDesc: '',
                remarks: '',
                expectedArrivalDate: '',
                factoryNumber: '',
                returnBy: '',
                createdDate: '',
                batchNo: '',
                returnStatus: '',
                linkMan: '',
                linkPhone: '',
                isBorrow: '',
                auditOpinion: '',
                auditRemarks: '',
                returnMaterialDetailDOList: []
            };
            $scope.tableConfig = { // 1、主列表
                fixedWidth: 280,
                scrollWidth: 1800,
                tableCol: [{
                        type: "",
                        name: "归还单号",
                        dataField: "code",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowCode",
                        width: 140,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceInformationMember",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "吊机编号",
                        dataField: "crantNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出仓库",
                        dataField: "warehouseOut",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出库区",
                        dataField: "warehouseAreaOut",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借拆件原因说明",
                        dataField: "borrowReasonDesc",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态", // 出库状态:0未出库，1部分出库，2已出库
                        dataField: "statusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核状态", // 出库状态:0待审批，1审批通过，2审批失败
                        dataField: "returnStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remarks",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "预计归还日期",
                        dataField: "expectedArrivalDateShow", // 日期格式转换
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出厂编号",
                        dataField: "factoryNumber",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "归还人",
                        dataField: "returnBy",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "批次号",
                        dataField: "batchNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 200,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.tableItemConfig = { // 2、新增归还单页面-借用单列表
                fixedWidth: 200,
                scrollWidth: 1450,
                tableCol: [{
                        type: "",
                        name: "借用单号",
                        dataField: "code",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceInformationMember",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "吊机编号",
                        dataField: "crantNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入仓库",
                        dataField: "warehouseLeadIn",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入库区",
                        dataField: "warehouseAreaLeadIn",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借拆件原因说明",
                        dataField: "borrowReasonDesc",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remarks",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "预计归还日期",
                        dataField: "expectedArrivalDateShow", // 日期格式转换
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出厂编号",
                        dataField: "factoryNumber",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用人",
                        dataField: "borrower",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "批次号",
                        dataField: "batchNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 870,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 150,
                        dataField: "materialDesc",
                        needInput: false
                    },
                    {
                        name: "数量",
                        width: 100,
                        dataField: "amount",
                        needInput: true
                    },
                    {
                        name: "备注",
                        width: 200,
                        dataField: "remarks",
                        needInput: false
                    },
                ]
            };

            // 退回单按钮的权限code
            var btnPermissionCode = {
                borrowBackAdd: window.ActionCode.borrowBackAdd,
                borrowBackDel: window.ActionCode.borrowBackDel,
                borrowBackEdit: window.ActionCode.borrowBackEdit,
                borrowBackPrint: window.ActionCode.borrowBackPrint,
                borrowBackExport: window.ActionCode.borrowBackExport,
                borrowBackAudit: window.ActionCode.borrowBackAudit, // 审核
                borrowBackUpload: window.ActionCode.borrowBackUpload, // 在线上传
                borrowBackFinish: window.ActionCode.borrowBackFinish, // 完成
            };

            // 退回单按钮的权限
            $scope.btnPermission = {
                borrowBackAdd: true,
                borrowBackDel: true,
                borrowBackPrint: true,
                borrowBackExport: true,
                borrowBackAudit: true,
                borrowBackFinish: true,
            };

            // 查看用户的按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    }
                };
            };

            // 切换tab
            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                $scope.deleteIdList = []; // 清空要删除的零件id数组
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            // 初始化数据
            function initData() {
                $scope.tabFlag = {};
                $scope.steps.curStep = 0;
                $scope.orderObj = {
                    id: '',
                    borrowCode: '',
                    code: '',
                    serviceInformationMember: '',
                    crantNo: '',
                    warehouseOut: '',
                    warehouseAreaOut: '',
                    borrowReasonDesc: '',
                    remarks: '',
                    expectedArrivalDate: '',
                    factoryNumber: '',
                    returnBy: '',
                    createdDate: '',
                    batchNo: '',
                    returnStatus: '',
                    linkMan: '',
                    linkPhone: '',
                    isBorrow: '',
                    auditOpinion: '',
                    auditRemarks: '',
                    returnMaterialDetailDOList: []
                };
                $scope.markInfo.allCheckedList = false; // 清除主列表上的全选
                $scope.toolbarConfig.showMateriel = false;
            }


            /* 主列表新增 */
            $scope.addApply = function () {
                // 调用新增归还单列表接口
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                $scope.changeTab(1);
                var service = "device";
                var reqUrl = "/returnMaterial/getInsertList";
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage,
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.expectedArrivalDateShow = $filter("YbDate")(item.expectedArrivalDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createdDateShow = $filter("YbDate")(item.createdDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataBorrowInList = resp.value.list;
                });
            };

            /* 主列表单条打印 */
            $scope.printSingle = function (item) {
                var param = {
                    printType: "BorrowBack",
                    cusParam: { ids: [item.id] }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };


            /* 主列表多条打印 */
            $scope.batchPrint = function () {
                const billIds = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "BorrowBack",
                    cusParam: { ids: billIds }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            /* 获取新增详情页信息 */
            $scope.selDeliveryNotice = function (item) {
                $scope.steps.curStep = 1;
                ybHttp.Get('device', '/borrowMaterial/get', {
                    id: item.id
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj = resp.value;
                    $scope.orderObj.expectedArrivalDateShow = $filter("YbDate")(resp.value.expectedArrivalDate, 'yyyy-MM-dd HH:mm:ss');
                    $scope.orderObj.warehouseOut = resp.value.warehouseLeadIn;
                    $scope.orderObj.warehouseAreaOut = resp.value.warehouseAreaLeadIn;
                    $scope.orderObj.returnBy = resp.value.borrower;
                    $scope.orderObj.returnMaterialDetailDOList = resp.value.borrowMaterialDetailDOList;
                    // 保存借用单号和id
                    $scope.orderObj.borrowCode = resp.value.code;
                    $scope.orderObj.borrowId = resp.value.id;
                });
            };

            /* 上一步 */
            $scope.prevStep = function () {
                $scope.steps.curStep = 0;
            };

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            /* 批量删除零件 */
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.returnMaterialDetailDOList.length; i < len; i++) {
                    if (!!$scope.orderObj.returnMaterialDetailDOList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.returnMaterialDetailDOList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.returnMaterialDetailDOList[i].isChecked) {
                            $scope.orderObj.returnMaterialDetailDOList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.returnMaterialDetailDOList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };


            /* 生成归还单 */
            $scope.createBorrowBack = function () {
                var service = "device";
                var reqUrl = "/returnMaterial/add";
                ybHttp.Post(service, reqUrl, $scope.orderObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            }

            // 归还单数据列表
            function getDataList(curPage) {
                // 每次请求数据清空要导出的退回单id数组
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/returnMaterial/list";
                //遍历搜索条件对象里的空值并删除  不然搜索不出数据
                Object.keys($scope.condition).forEach(function (key) {
                    if (!$scope.condition[key]) delete $scope.condition[key];
                });
                var param = {
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: curPage || $scope.pageInfo.curPage,
                    filters: $scope.condition
                };
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.expectedArrivalDateShow = $filter("YbDate")(item.expectedArrivalDate, 'yyyy-MM-dd HH:mm:ss');
                        item.createdDateShow = $filter("YbDate")(item.createdDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = $filter("ProgressStatus")(item.status, "outStore");
                        item.returnStatusShow = $filter("ProgressStatus")(item.returnStatus, "borrowBackAudit");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            // 点击列的事件
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            // 展示和隐藏高级搜索
            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            // 打印订单
            $scope.printBill = function (item) {
                var param = {
                    billId: [item.id],
                    printType: "ServiceBorrowIn"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            // 搜索退回单列表
            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            // 重置搜索条件
            $scope.reset = function () {
                $scope.condition = {};
            };

            /* 主列表的批量删除 */
            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked && item.returnStatus !== '1') {
                        deleteList.push({
                            id: item.id
                        });
                    } else if (item.isChecked && item.returnStatus === '1') {
                        deleteList = [];
                        return;
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除的归还单（选择状态不是审核通过的归还单进行删除）', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/returnMaterial/batchDelete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            // 单个删除归还单
            $scope.delBorrowBack = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteBorrowBackService({
                        id: item.id
                    }).then(function (res) {
                        if (res) {
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        }
                    });
                })
            };

            // 调用删除归还单接口
            function deleteBorrowBackService(id) {
                var url = '/returnMaterial/delete';
                return ybHttp.Post('device', url, id).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return true;
                })
            }


            // 编辑归还单
            $scope.editBorrowBack = function (item) {
                getDetail(item).then(function (data) {
                    if (data) {
                        $scope.tabFlag.type = 2;
                        $scope.tabFlag.name = tabFlag[2];
                        $scope.orderObj = data;
                        $scope.orderObj.createdDate = new Date(data.createdDate);
                        $scope.orderObj.expectedArrivalDate = new Date(data.expectedArrivalDate);
                        $scope.changeTab(2);
                    }
                })
            }

            $scope.$watch('orderObj.returnMaterialDetailDOList.length', function () {
                setMaterialDesc();
            });

            function setMaterialDesc() {
                if (!$scope.orderObj.returnMaterialDetailDOList || $scope.orderObj.returnMaterialDetailDOList.length == 0) {
                    return;
                }
                angular.forEach($scope.orderObj.returnMaterialDetailDOList, function (item) {
                    item.materialNo = item.materialsNo ? item.materialsNo : item.materialNo;
                    item.materialDesc = item.materialsDes ? item.materialsDes : item.materialDesc;
                });
            }

            /* 主列表审核 */
            $scope.auditApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.orderObj.returnStatus = $filter("ProgressStatus")(data.returnStatus, "borrowBackAudit");
                    $scope.orderObj.auditOpinion = data.auditOpinion;
                    $scope.changeTab(4);
                });
            };


            /* 主列表完成 */
            $scope.finishApply = function (id) {
                ybWidget.ShowMessage("确定要完成吗？", MESG_TYPE.Ask).then(function () {
                    finishBorrowBackService({
                        id: id
                    }).then(function (res) {
                        if (res) {
                            ybWidget.ShowToaster('success', '操作成功');
                            getDataList();
                        }
                    });
                })
            };


            // 调用完成接口
            function finishBorrowBackService(id) {
                var url = '/returnMaterial/finish';
                return ybHttp.Post('device', url, id).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return true;
                })
            }


            /* 审核通过 */
            $scope.auditPurchase = function (type, id, message) {
                var service = "device";
                var reqUrl = "/returnMaterial/audit";
                if (type === "refuse") {
                    if (!message) {
                        ybWidget.ShowMessage('请输入审核意见');
                        $scope.submitted = true;
                        return;
                    }
                    reqUrl = "/returnMaterial/refuse";
                }
                var param = {
                    id: id,
                    auditOpinion: message
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (type === "pass") {
                        ybWidget.ShowMessage("审核成功!");
                    }

                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.orderObj.auditOpinion = "";
                });
            };

            $scope.uploadBorrowBack = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    isImage: true,
                    maxImgSize: 10,
                    importReqService: "device",
                    importReqUrl: "/returnMaterial/uploadImage",
                    importErrorUrl: "",
                    billId: item.id
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            $scope.downloadBorrowBack = function (item) {
                ybWidget.ViewImage({
                    FileName: '归还单明细预览',
                    FileUrl: item.imageName
                })
            };


            // 查看详情
            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (data) {
                        $scope.orderObj = data;
                        $scope.orderObj.returnStatus = $filter("ProgressStatus")(data.returnStatus, "borrowBackAudit");
                        $scope.changeTab(3);
                    }
                });
            }


            /* 删除零件 */
            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.returnMaterialDetailDOList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialNo);
                });
            };

            /* 批量删除零件 */
            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.returnMaterialDetailDOList.length; i < len; i++) {
                    if (!!$scope.orderObj.returnMaterialDetailDOList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.returnMaterialDetailDOList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.returnMaterialDetailDOList[i].isChecked) {
                            $scope.orderObj.returnMaterialDetailDOList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.returnMaterialDetailDOList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            /* 零件数量合计 */
            $scope.countTotal = function (item) {
                item.qtyErr = false;
                if (!item.amount || parseFloat(item.amount) <= 0) {
                    item.qtyErr = true;
                }
                item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.amount, item.price), 2);
            };


            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "";
                if (!!$scope.orderObj.id) {
                    reqUrl = "/returnMaterial/update";
                }
                if (!$scope.orderObj.returnMaterialDetailDOList || $scope.orderObj.returnMaterialDetailDOList.length == 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                for (var i = 0, len = $scope.orderObj.returnMaterialDetailDOList.length; i < len; i++) {
                    $scope.orderObj.returnMaterialDetailDOList[i].qtyErr = false;
                    if (!$scope.orderObj.returnMaterialDetailDOList[i].amount || parseFloat($scope.orderObj.returnMaterialDetailDOList[i].amount) <= 0) {
                        $scope.orderObj.returnMaterialDetailDOList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }
                setMaterialDesc();
                var param = angular.copy($scope.orderObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            $scope.actionUrl = ybHttp.RequestUrl("device", "/threeGuaranteesPur/download");


            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            $scope.selectAll = function () {
                for (var i = 0; i < $scope.dataList.length; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allCheckedList;
                }
                getBillIds();
            };

            /* 获取详情 */
            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/returnMaterial/get', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    setMaterialDesc();
                    return resp.value;
                });
            }

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    $scope.orderObj.warehouseOut = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.orderObj.warehouseOut = "";
                $scope.orderObj.warehouseAreaOut = "";
            };

            /* 清除库区 */
            $scope.clearArea = function () {
                $scope.orderObj.warehouseAreaOut = "";
            }

            /* 选择库区 */
            $scope.selectArea = function () {
                if (!$scope.orderObj.warehouseOut) {
                    ybWidget.ShowToaster('error', '请选择领出仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.orderObj.warehouseOut;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.orderObj.warehouseAreaOut = data.areaCode;
                })
            };


            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }]);
})(window, window.angular);